package com.typhoon.extend.service.impl;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.typhoon.extend.constant.ExtendEntityError;
import com.typhoon.extend.dao.AccountDao;
import com.typhoon.extend.dto.AccountDto;
import com.typhoon.extend.dto.ResponseDto;
import com.typhoon.extend.dto.request.LoginReq;
import com.typhoon.extend.entity.Account;
import com.typhoon.extend.service.AccountService;
import com.typhoon.extend.util.BeanUtils;
import com.typhoon.extend.util.encrypt.MD5Util;

@Service("accountService")
public class AccountServiceImpl implements AccountService {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(AccountServiceImpl.class);

	@Resource
	AccountDao accountDao;
	
	@Override
	public ResponseDto<AccountDto> doLogin(LoginReq req) {
		ResponseDto<AccountDto> resp = new ResponseDto<>();
		if(null == req || StringUtils.isBlank(req.getAccountCode()) || StringUtils.isBlank(req.getPassword())) {
			return resp.error(ExtendEntityError.ILLEGAL_ARGUMENT_ERROR);
		}
		Account account = this.accountDao.queryByCode(req.getAccountCode());
		if(null == account) {
			LOGGER.warn("accountCode:{} not exist",req.getAccountCode());
			return resp.error(ExtendEntityError.ACCOUNT_NOT_EXIST);
		}
		if(!account.getAccountCode().equals(req.getAccountCode())) {
			return resp.error(ExtendEntityError.ACCOUNT_ERROR);
		}
		if(!account.getPassword().equals(MD5Util.toMD5(req.getPassword()))) {
			LOGGER.error("account:{}password not match",req.getAccountCode());
			return resp.error(ExtendEntityError.PASSWORD_ERROR);
		}
		return resp.success(BeanUtils.toBean(account, AccountDto.class));
	}

	@Override
	public AccountDto queryByCode(String accountCode) {
		return BeanUtils.toBean(this.accountDao.queryByCode(accountCode), AccountDto.class);
	}

}
